import {combineReducers} from 'redux-immutable';
import Immutable from 'immutable';
import * as actions from './actions';
import {
    GET_CURRENT_USER_PAGE_PERMISSIONS_BEGIN,
    GET_CURRENT_USER_PAGE_PERMISSIONS_SUCCESS,
    GET_CURRENT_USER_PAGE_PERMISSIONS_FAIL
} from 'Shared/actions/currentUserContext';
import {DEFAULT_QUERY_OPTION, DEFAULT_SUBMIT_DATA, HISTORY_DEFAULT_QUERY_OPTION} from './constants';
import {claimSettlementBillStatus} from '../Enum';
import {generateRowSpanDatas} from './utils';
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
export const permission = (state, action) => {
    switch(action.type) {
        case GET_CURRENT_USER_PAGE_PERMISSIONS_BEGIN:
            return state.merge(
                Immutable.fromJS({
                    isFetching: true,
                    message: ''
                })
            );
        case GET_CURRENT_USER_PAGE_PERMISSIONS_SUCCESS:
            return state.merge(
                Immutable.fromJS({
                    isFetching: false,
                    message: '',
                    data: action.data
                })
            );
        case GET_CURRENT_USER_PAGE_PERMISSIONS_FAIL:
            return state.merge(
                Immutable.fromJS({
                    isFetching: false,
                    message: action.message
                })
            );
        default:
            return state;
    }
};

const initData = (state, action) => {
    switch(action.type) {
        case actions.GET_INIT_BEGIN:
            return state.merge({
                isFetching: true,
                message: ''
            });

        case actions.GET_INIT_SUCCESS:
            return state.merge({
                isFetching: false,
                isDealerUser: action.data.isDealerUser,
                tradeMethods: action.data.tradeMethods || EMPTY_ARRAY,
                manucturers: action.data.manucturers || EMPTY_ARRAY,
                message: '',
                currentUserName: action.data.currentUserName,
                isMoneyVisible: action.data.isMoneyVisible,
            });
        case actions.GET_INIT_FAIL:
            return state.merge({
                message: action.message,
                isFetching: false
            });

        default:
            return state;
    }
};

const list = (state, action) => {
    switch(action.type) {
        case actions.GET_LIST_BEGIN:
            return state.merge({
                isFetching: true,
                message: '',
                total: 0
            });
        case actions.GET_LIST_SUCCESS:
            return state.merge({
                isFetching: false,
                total: action.data.totalElements,
                message: '',
                data: action.data.content
            });
        case actions.GET_LIST_FAIL:
            return state.merge({
                isFetching: false,
                total: 0,
                message: action.message || '',
                data: EMPTY_ARRAY
            });
        default:
            return state;
    }
};

const historyList = (state, action) => {
    switch(action.type) {
        case actions.GET_HISTORY_LIST_BEGIN:
            return state.merge({
                isFetching: true,
                message: '',
                total: 0
            });
        case actions.GET_HISTORY_LIST_SUCCESS:
            return state.merge({
                isFetching: false,
                total: action.data.totalElements,
                message: '',
                data: action.data.content
            });
        case actions.GET_HISTORY_LIST_FAIL:
            return state.merge({
                isFetching: false,
                total: 0,
                message: action.message || '',
                data: EMPTY_ARRAY
            });
        default:
            return state;
    }
};

const queryCondition = (state, action) => {
    switch(action.type) {
        case actions.SAVE_QUERY_CONDITION:
            return state.set(action.name, action.value);
        case actions.GET_INIT_SUCCESS:
            if(action.data.isDealerUser)
                return state.set('status', [claimSettlementBillStatus.开票通知]);
            return state;
        case actions.CHANGE_BATCH:
            if(state)
                return state.set('status', [claimSettlementBillStatus.开票通知]);
            return state;
        case actions.SELECT_DEALER_QUERY:
            return state.merge({
                ...action.data
            });
        case actions.RESET_QUERY_PANEL: {
            const {pageSize, sortField, isDesc} = state.toJS();
            return Immutable.fromJS({
                ...DEFAULT_QUERY_OPTION,
                pageSize,
                sortField,
                isDesc
            });
        }
        case actions.GET_LIST_SUCCESS:
            return state.withMutations(map =>
                map
                    .set('pageSize', action.condition.pageSize)
                    .set('sortField', action.condition.sortField)
                    .set('isDesc', action.condition.isDesc)
            );

        default:
            return state;
    }
};

const historyQueryCondition = (state, action) => {
    switch(action.type) {
        case actions.SELECT_HISTORY_DEALER_QUERY:
            return state.merge({
                ...action.data
            });
        case actions.SAVE_HISTORY_QUERY_CONDITION:
            return state.set(action.name, action.value);
        case actions.RESET_HISTORY_QUERY_PANEL: {
            const {pageSize, sortField, isDesc} = state.toJS();
            return Immutable.fromJS({
                ...HISTORY_DEFAULT_QUERY_OPTION,
                pageSize,
                sortField,
                isDesc
            });
        }
        case actions.GET_HISTORY_LIST_SUCCESS:
            return state.withMutations(map =>
                map
                    .set('pageSize', action.condition.pageSize)
                    .set('sortField', action.condition.sortField)
                    .set('isDesc', action.condition.isDesc)
            );

        default:
            return state;
    }
};

const queryBySort = (state, action) => {
    switch(action.type) {
        case actions.GET_LIST_SUCCESS:
            return state.merge(action.condition);
        default:
            return state;
    }
};

const historyQueryBySort = (state, action) => {
    switch(action.type) {
        case actions.GET_HISTORY_LIST_SUCCESS:
            return state.merge(action.condition);
        default:
            return state;
    }
};

const detail = (state, action) => {
    switch(action.type) {
        case actions.GET_DETAIL_BEGIN:
            return state.merge({
                isFetching: true,
                message: '',
                data: EMPTY_OBJECT
            });

        case actions.GET_DETAIL_SUCCESS:
            return state.merge({
                isFetching: false,
                message: '',
                data: Object.assign({}, action.data, {
                    details: generateRowSpanDatas(action.data.details, 'code',
                        ['claimId'])
                })
            });

        case actions.CLEAR_DATA:
        case actions.GET_DETAIL_FAIL:
            return state.merge({
                isFetching: false,
                message: action.message,
                data: EMPTY_OBJECT
            });

        default:
            return state;
    }
};


const submitData = (state, action) => {
    switch(action.type) {
        case actions.SAVE_SUBMIT_CONDITION:
            return state.set(action.name, action.value);
        case actions.CLEAR_DATA:
            return Immutable.fromJS(DEFAULT_SUBMIT_DATA);
        case actions.GET_DETAIL_SUCCESS:
            return state.merge({
                ...action.data,
                department: action.data.department || '服务支援部'
            });
        case actions.UPDATE_DETAIL: {
            return state.setIn(['details'], action.newDetails);
        }
        case actions.UPDATE_ATTACHMENTS:
            return state.updateIn(['attachments'], obj => obj.push(Immutable.fromJS(action.data)));
        case actions.REMOVE_ATTACHMENTS: {
            const index = state.get('attachments').findIndex(item => item.get('fileId') === action.id);
            if(index === -1)
                return state;
            return state.updateIn(['attachments'], list => list.splice(index, 1));
        }
        default:
            return state;
    }
};


const brands = (state, action) => {
    switch(action.type) {
        case actions.GET_BRANDS_BEGIN:
            return state.merge({
                isFetching: true,
                message: ''
            });

        case actions.GET_BRANDS_SUCCESS:
            return state.merge({
                isFetching: false,
                data: action.data.content || [],
                message: ''
            });
        case actions.GET_BRANDS_FAIL:
            return state.merge({
                message: action.message,
                isFetching: false
            });
        default:
            return state;
    }
};

const isBatch = (state, action) => {
    switch(action.type) {
        case actions.CHANGE_BATCH: {
            return !state;
        }
        default:
            return state;
    }
};


const domainData = combineReducers({
    initData,
    permission,
    list,
    detail,
    brands,
    historyList
});
const appState = combineReducers({
    queryCondition,
    queryBySort,
    submitData,
    isBatch,
    historyQueryCondition,
    historyQueryBySort
});
export default combineReducers({
    domainData,
    appState,
});
